package io.kiki.sba.registry.server.metadata.resource;

import io.kiki.sba.registry.common.model.Response;
import io.kiki.sba.registry.store.api.meta.RecoverConfigRepository;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * @author xiaojian.xj
 * @version : RecoverConfigResource.java, v 0.1 2021年09月25日 00:02 xiaojian.xj Exp $
 */
@Path("api/recover/config")
@Produces(MediaType.APPLICATION_JSON)
public class RecoverConfigResource {

    private static final Logger logger = LoggerFactory.getLogger(RecoverConfigResource.class);

    @Autowired
    private RecoverConfigRepository recoverConfigRepository;

    @POST
    @Path("/save")
    public Response saveConfig(@FormParam("table") String table, @FormParam("key") String key, @FormParam("recoverClusterId") String recoverClusterId) {
        if (StringUtils.isBlank(table) || StringUtils.isBlank(key) || StringUtils.isBlank(recoverClusterId)) {
            return Response.buildFailedResponse("table, key, recoverClusterId is not allow empty.");
        }

        boolean ret = recoverConfigRepository.save(table, key, recoverClusterId);

        logger.info("save recover config result:{}, table:{}, key:{}", ret, table, key);

        Response response = Response.buildSuccessResponse();
        response.setSuccess(ret);
        return response;
    }

    @POST
    @Path("/remove")
    public Response removeConfig(@FormParam("table") String table, @FormParam("key") String key) {
        if (StringUtils.isBlank(table) || StringUtils.isBlank(key)) {
            return Response.buildFailedResponse("table and key is not allow empty.");
        }

        boolean ret = recoverConfigRepository.remove(table, key);

        logger.info("remove recover config result:{}, table:{}, key:{}", ret, table, key);

        Response response = Response.buildSuccessResponse();
        response.setSuccess(ret);
        return response;
    }
}
